import json

from django.db.models import Q
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from unicodedata import category
from goods import models, ser


class MyPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'


class GoodsView(ListAPIView):
    queryset = models.Goods.objects.all()
    serializer_class = ser.GoodsSerializer
    pagination_class = MyPagination

    def get_queryset(self):
        cate = self.request.query_params.get('cate')
        price_range = self.request.query_params.get('price_range')
        sort = self.request.query_params.get('sort')
        keyword = self.request.query_params.get('keyword')
        query = Q()
        if cate:
            query &= Q(categories__id=cate)
        if price_range:
            query &= Q(course_type=price_range)
        if sort:
            return self.queryset.filter(query).order_by("-"+sort)
        if keyword:
            query &= (Q(name__icontains=keyword) | Q(description__icontains=keyword) | Q(brief__icontains=keyword) |
                      Q(teacher__name__icontains=keyword))
        return self.queryset.filter(query)


class GoodsDetailView(APIView):
    def get(self, request):
        pk = request.query_params.get('id')
        if not pk:
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        info = models.Goods.objects.filter(id=pk, is_show=True, is_del=False).first()
        if not info:
            return Response({
                'code': 400,
                'msg': '课程不存在'
            })
        res = ser.GoodsSerializer(info)
        return Response({
            'code': 200,
            'msg': 'ok',
            'data': res.data
        })

from majing import models, ser


class AddCartView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        goods_id = request.data.get("goods_id")
        if not goods_id:
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        info = models.Goods.objects.filter(id=goods_id, is_show=True, is_del=False).first()
        if not info:
            return Response({
                'code': 400,
                'msg': '课程不存在'
            })
        cart_key = 'goods:cart:cart_list:' + str(user.id)
        goods_key = 'goods:' + str(goods_id)
        conn = get_redis_connection('cart')
        if conn.hexists(cart_key, goods_key):
            return Response({
                'code': 400,
                'msg': '购物车中已存在此课程'
            })
        goods_info = {
            'goods_id': goods_id,
            'goods_name': info.name,
            'goods_img': str(info.img),
            'goods_price': float(info.price),
            'selected': 1,
        }
        conn.hset(cart_key, goods_key, json.dumps(goods_info))
        return Response({
            'code': 200,
            'msg': 'ok',
        })


class CartList(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        user = request.user
        cart_key = 'goods:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        cart_list = []
        for goods_key, goods_info in cart_info.items():
            goods_info = json.loads(goods_info.decode('utf-8'))
            cart_list.append(goods_info)
        return Response({
            'code': 200,
            'msg': 'ok',
            'data': cart_list
        })


